package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.*;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 加载文章详情的初始化配置信息，比如关注、喜欢、不喜欢等
     *
     * @param dto
     * @return
     */
    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    ApCollectionMapper apCollectionMapper;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(new HashMap<>());
        }
        boolean iscollection=false,isfollow=false;

        //2 查询是否关注
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(new HashMap<>());
        }
        // 查询作者对应的Apuser主键
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.okResult(new HashMap<>());
        }

        ApUserFollow userFollow = userFeign.findByUserIdAndFollowId(user.getId(), apAuthor.getUserId());
        if (userFollow != null) {
            isfollow = true;
        }

        //3 查询是否不喜欢/点赞
        ApArticleRelationDto apDto = new ApArticleRelationDto();
        apDto.setArticleId(dto.getArticleId());
        apDto.setEntryId(user.getId());  // 用户id
        apDto.setType((short) 1);
        Map map = behaviorFeign.findApArticleRelation(apDto);

        //4 查询是否收藏
        if (map.get("entryId") != null) {
            ApCollection apCollection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId,dto.getArticleId())
                    .eq(ApCollection::getEntryId, map.get("entryId") )
                    .eq(ApCollection::getType, ApCollection.Type.ARTICLE.getCode() )
            );

            if (apCollection != null) {
                iscollection = true;
            }
        }

        //5 封装结果返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("iscollection", iscollection);
        resultMap.put("isfollow", isfollow);
        resultMap.putAll(map);

        return ResponseResult.okResult(resultMap);
    }


    /**
     * 保存app文章
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        // 参数检查
        if (articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1 保存article 文章数据， 设置作者id
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        // 设置作者的id
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getName, apArticle.getAuthorName()));
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());

        if (articleDto.getId() == null) {  // 保存

            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            // 保存
            save(apArticle);  // 返回ID

            //2 保存article_config 数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);
            // 文章id
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //3 保存文章article_content 数据
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(articleDto.getContent());
            // 文章ID
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(apArticleContent);


        }else { // 修改

            // 查询文章
            ApArticle article = getById(articleDto.getId());
            if (article == null) {
                log.info("ApArticle getById is null: {}", articleDto.getId());

                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            // 修改 apArticle
            updateById(apArticle);

            // 修改 apArticleContent
            ApArticleContent articleContent = apArticleContentMapper.selectOne( Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,articleDto.getId() ));
            if (articleContent == null) {
                log.info("articleContent getById is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(articleContent);

        }

        //4 返回结果  文章保存后的主键 ID
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.检查参数
        if (dto == null){
            dto = new ArticleHomeDto();
        }

        //参数值处理
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        Integer size = dto.getSize();
        if (size == null || size > 50){
            size = Math.min(size, 50);
        }
        if (size <= 0 ){
            dto.setSize(10);
        }
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() ==null){
            dto.setMaxBehotTime(new Date());
        }
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        List<ApArticle> list = apArticleMapper.loadArticleList(dto, loadtype);
        ResponseResult result = ResponseResult.okResult(list);
        result.setHost(webSite);
        return result;

    }

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //1.参数校验
        if (dto == null && dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询文章
        ApArticleConfig config = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId,dto.getArticleId()));

        if (config == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断上下架和删除
        if (config.getIsDown() || config.getIsDelete()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已删除或已下架");
        }
        ApArticle article = getById(dto.getArticleId());
        if (article == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        ApArticleContent content = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId,dto.getArticleId()));
        if (content == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("config",config);
        resultMap.put("content",content);

        return ResponseResult.okResult(resultMap);
    }
}